package v1

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"jwgin/model/mysql"
	"jwgin/service"
	signs "jwgin/utils/sign"
)

// 会员管理
type users struct{}

func (l *users) Routers(Router *gin.RouterGroup) (R gin.IRoutes) {
	//资源列表
	Router.GET("user", l.get)   //用户信息
	Router.POST("user", l.post) //更新
	return Router
}

//获取用户信息
func (users) get(c *gin.Context) {
	uid, b2ol := c.Get("UserID")
	if !b2ol {
		RespErr(c, errors.New("请重新登录"))
		return
	}
	u := map[string]interface{}{}
	if err := service.G.Model(&mysql.User{}).Select("id,username,account,bean,addtime,uptime").Where("id = ? ", uid).First(&u).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			RespErr(c, errors.New("请求出错"))
			return
		} else {
			RespErr(c, errors.New("非法操作"))
			return
		}
	}
	RespSucc(c, u)
}

//修改用户信息
func (users) post(c *gin.Context) {

	uid, b2ol := c.Get("UserID")
	if !b2ol {
		RespErr(c, errors.New("请重新登录"))
		return
	}

	q := &mysql.User{}
	if err := c.ShouldBind(q); err != nil {
		RespErr(c, err)
		return
	}

	h := &mysql.User{}
	if err := service.G.Where("id = ? ", uid).First(h).Error; err != nil {
		RespErr(c, errors.New("请求出错"))
		return
	}

	var err error
	if len(q.Password) > 0 {
		if len(q.Password) > 16 || len(q.Password) < 6 {
			RespErr(c, errors.New("密码6-16位"))
			return
		}
		pass := signs.HmacSha256(h.Salt, q.Password)
		err = service.G.Model(&mysql.User{}).Where("id = ? ", uid).Update("username", q.Username).Update("password", pass).Error
	} else {
		err = service.G.Model(&mysql.User{}).Where("id = ? ", uid).Update("username", q.Username).Error
	}
	if err != nil {
		RespErr(c, errors.New("请求出错"))
		return
	}
	RespSucc(c, nil)

}
